<?php


namespace app\common\repositories\system\merchant;

use app\common\dao\system\merchant\MerchantCategoryIntentionDao;
use app\common\model\store\StoreCategory;
use app\common\model\system\merchant\Merchant;
use app\common\repositories\BaseRepository;
use app\common\repositories\store\StoreCategoryRepository;
use crmeb\jobs\SendSmsJob;
use crmeb\services\SmsService;
use FormBuilder\Factory\Elm;
use \app\common\model\system\merchant\MerchantCategoryIntention;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Queue;
use think\facade\Route;

/**
 * @mixin MerchantCategoryIntentionDao
 */
class MerchantCategoryIntentionRepository extends BaseRepository
{

    public function __construct(MerchantCategoryIntentionDao $dao)
    {
        $this->dao = $dao;
    }

    public function lst(?int $merId,array $where, $page, $limit)
    {
        $query = $this->dao->search($merId,$where);
        $count = $query->count();
        $data = $query->page($page, $limit)
            ->setOption('field', [])
            ->with([
               'merchant' => function ($query) {
                    $query->field('mer_id,mer_name,real_name,mer_phone');
                },
                'storeCategoryTwo' => function ($query) {
                    $query->field('store_category_id,cate_name,pid,margin,commission_rate');
                },
            ])
            ->field('mer_category_intention_id,ci.mer_id,ci.status,lvl_two,fail_msg,ci.mark,images,ci.create_time')
            ->order('ci.create_time desc')
            ->select();
        // 拼接商品分类
        foreach ($data as $v){
            $v['images_arr'] =$v['images'] ? explode(',',$v['images']) :[];
            if (!empty($v['storeCategoryTwo'])) {
                $cate_name = app()->make(StoreCategoryRepository::class)->getAllFatherName($v['storeCategoryTwo']['store_category_id']);
                $v['storeCategoryTwo']['pj_cate_name'] = $cate_name;
            }
        }
        $list = $data;
        return compact('count', 'list');
    }



    public function merLst(?int $merId,array $where, $page, $limit)
    {
        $query = $this->dao->search($merId,$where);
        $count = $query->count();
        $data = $query->page($page, $limit)
            ->setOption('field', [])
            ->with([
                'storeCategoryOne' => function ($query) {
                    $query->field('store_category_id,cate_name,pid');
                },
                'storeCategoryTwo' => function ($query) {
                    $query->field('store_category_id,cate_name,pid,margin,commission_rate');
                },
            ])
            ->field('mer_category_intention_id,ci.mer_id,ci.status,lvl_one,lvl_two,fail_msg,ci.mark,images,ci.create_time')
            ->order('ci.mer_category_intention_id desc')
            ->select();

       // $margin = (new MerchantCategoryIntention())->getHighestMargin($merId);
        $merchant =  request()->merchant();
        // 拼接商品分类
        foreach ($data as $v){
            $v['images_arr'] =$v['images'] ? explode(',',$v['images']) :[];
            $where2=[
                ['pid','=',$v['lvl_two']],
            ];
            $v['is_pay_margin'] = false;
            if($merchant->margin < $v['storeCategoryTwo']['margin'] && $v['status'] == 1){
                $v['is_pay_margin'] = true;
            }

            $v['lvl_three_string'] = app()->make(StoreCategoryRepository::class)->getThreeFatherName($where2);
        }
        $list = $data;
        return compact('count', 'list');
    }

    public function detail($id, ?int $uid, $with =[])
    {
        $where = ['mer_intention_id' => $id];
        if (!is_null($uid)) {
            $where['uid'] = $uid;
        }
        return $this->dao->search($where)->with($with)->find();
    }

    public function updateIntention($id, array $data)
    {
        if ($this->dao->existsWhere(['mer_intention_id' => $id, 'status' => '1']))
            throw new ValidateException('当前状态不能修改');
        $data['images'] = implode(',', (array)$data['images']);
        $data['door_img'] = implode(',', (array)$data['door_img']);
        $data['cashier_img'] = implode(',', (array)$data['cashier_img']);
        $data['in_store_img'] = implode(',', (array)$data['in_store_img']);
        $data['status'] = 0;
        $data['fail_msg'] = '';
        return $this->dao->update($id, $data);
    }

    public function markForm($id)
    {
        $data = $this->dao->get($id);
        $form = Elm::createForm(Route::buildUrl('systemCategoryMerchantIntentionMark', ['id' => $id])->build());
        $form->setRule([
            Elm::textarea('mark', '备注', $data['mark'])->required(),
        ]);
        return $form->setTitle('修改备注');
    }

    public function statusForm($id)
    {
        $form = Elm::createForm(Route::buildUrl('systemCategoryIntentionStatus', ['id' => $id])->build());
        $form->setRule([
            Elm::select('status', '审核状态', 1)->options([
                ['value' => 1, 'label' => '同意'],
                ['value' => 2, 'label' => '拒绝'],
            ])->control([
                [
                    'value' => 2,
                    'rule' => [
                        Elm::textarea('fail_msg', '失败原因', '信息填写有误')
                    ]
                ]
            ]),
        ]);
        return $form->setTitle('修改审核状态');
    }

    public function updateStatus($id, $data)
    {
        $intention = $this->dao->get($id);
        if (!$intention)
            throw new ValidateException('信息不存在');
        if ($intention['status'])
            throw new ValidateException('状态有误,修改失败');

        $StoreCategory = (new StoreCategory())->where('store_category_id',$intention->lvl_two)->find();
        if (!$StoreCategory)
            throw new ValidateException('该类目不存在');
//        $smsData = [
//            'date' => date('m月d日', strtotime($intention->create_time)),
//            'mer' => $intention['mer_name'],
//            'phone' => $intention['phone'],
//            'pwd' => $password ?? '',
//            'site_name' => systemConfig('site_name'),
//        ];
        $smsData = [];
        if ($data['status'] == 2) {
            $smsData = [
                'phone' => $intention['phone'],
                'date' => date('m月d日', strtotime($intention->create_time)),
                'mer' => $intention['mer_name'],
                'site' => systemConfig('site_name'),
            ];
        }
        Db::transaction(function () use ($intention,$StoreCategory, $data,$smsData) {
            if ($data['status'] == 1) {
                $data['fail_msg'] = '';
                $mer = (new Merchant())->where('mer_id',$intention['mer_id'])->find();
                if($mer->ot_margin < $StoreCategory->margin){
                    $mer->ot_margin = $StoreCategory->margin;
                    $mer->is_margin = 11;
                    $mer->save();
                }
                  //  Queue::push(SendSmsJob::class, ['tempId' => 'APPLY_MER_SUCCESS', 'id' => $smsData]);

            } else {
               // Queue::push(SendSmsJob::class, ['tempId' => 'APPLY_MER_FAIL', 'id' => $smsData]);
            }
            $intention->save($data);
        });
    }


    /**
     * @param int|null $merId
     * @param $name
     * @param $productType
     * @return array
     * @author: fupeng
     * @day: 2023/10/17
     */
    public function getFilter(?int $merId)
    {
        $result = [];
        $result[] = [
            'type' => '-1',
            'name' => '全部',
            'count' => $this->dao->search($merId, ['status' => '-1'])->count()
        ];
        $result[] = [
            'type' => '0',
            'name' => '待审核',
            'count' => $this->dao->search($merId, ['status' => '0'])->count()
        ];
        $result[] = [
            'type' => '1',
            'name' => '审核已通过',
            'count' => $this->dao->search($merId, ['status' => '1'])->count()
        ];
        $result[] = [
            'type' => '2',
            'name' => '审核未通过',
            'count' => $this->dao->search($merId, ['status' => '2'])->count()
        ];
        return $result;
    }


}
